package com.etoak.controller;

import com.etoak.common.vo.ResultVO;
import com.etoak.entity.Pic;
import com.etoak.service.PicService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
public class PicController {

    private static final String IMAGE_JPEG = "image/jpeg";

    private static final String IMAGE_PNG = "image/png";

    /**
     * application.yml 上传目录
     */
    @Value("${upload.dir}")
    private String uploadDirectory;

    /**
     * application.yml 图片地址前缀
     */
    @Value("${upload.path}")
    private String pathPrefix;

    @Autowired
    PicService picService;

    @PostMapping("/pic")
    public ResultVO<String> upload(MultipartFile file) {
        // 1.验证文件是否为空
        if (ObjectUtils.isEmpty(file) || file.isEmpty()) {
            return ResultVO.error("文件不能为空");
        }

        // 2.验证图片格式 只能是jpg 或 png
        String contentType = file.getContentType();
        if (!StringUtils.equalsIgnoreCase(contentType, IMAGE_JPEG) &&
                !StringUtils.equalsIgnoreCase(contentType, IMAGE_PNG)) {
            return ResultVO.error("图片只能是jpg或png格式!");
        }

        // 3.修改文件名称
        // 扩展名
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newFileName = uuid + "." + extension;

        // 4.创建上传目录
        File uploadDir = new File(this.uploadDirectory);
        if (uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 5.创建目标文件
        File destFile = new File(uploadDir, newFileName);

        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            return ResultVO.error("文件上传失败！");
        }

        String path = pathPrefix.endsWith("/") ? pathPrefix + newFileName : pathPrefix + "/" + newFileName;

        log.info("pic path - {}",path);
        Pic pic = new Pic();
        pic.setUrl(path);
        picService.addPic(pic);

        return ResultVO.success(path);
    }

}
